package com.lw.leetcode.bit.b;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * 面试题 05.04. 下一个数
 *
 * @author liw
 * @version 1.0
 * @date 2022/6/12 22:01
 */
public class FindClosedNumbers {

    public static void main(String[] args) {
        FindClosedNumbers test = new FindClosedNumbers();

        // [4, 1]
//        int n = 2;

        // [2, -1]
        int n = 1;

        int[] closedNumbers = test.findClosedNumbers(n);
        System.out.println(Arrays.toString(closedNumbers));
    }

    public int[] findClosedNumbers(int num) {
        long item = num;
        long a = 1;
        long b = 2;
        long max = -1;
        long min = -1;
        long sum = 0;
        long t = 0;
        for (int i = 0; i < 32; i++) {
            long v = item & a;
            if (v == a && (item & b) == 0) {
                max = (item | b) - sum - v + t;
                break;
            }
            sum += v;
            if (v > 0) {
                t = (t << 1) + 1;
            }
            a <<= 1;
            b <<= 1;
        }
        a = 1;
        b = 2;
        sum = 0;
        t = 0;
        for (int i = 0; i < 32; i++) {
            long v = item & a;
            if (v == 0 && (item & b) == b) {
                min = (item | a) - sum - (item & b) + t;
                break;
            }
            sum += v;
            if (v > 0) {
                t |= v;
            } else {
                t <<= 1;
            }
            a <<= 1;
            b <<= 1;
        }
        return new int[]{max > Integer.MAX_VALUE ? -1 : (int) max, min == -1 ? -1 : (int) min};
    }


}
